<template>
  <div>
    <div
      class="exportPdf-wrap"
      v-if="
        $auth('FEE_REVIEW.FEE_REVIEW_DETAIL') && paymentDetails.status == 70
      "
    >
      <a-button @click="exportToPDF" type="primary" class="exportPdf">{{
        $t('all.autotext1014')
      }}</a-button>
    </div>
    <div id="pdfContent" ref="pdfContent">
      <a-descriptions bordered size="small">
        <a-descriptions-item :label="$t('all.autotext1156')" :span="3">
          {{ paymentDetails.applyNo }}
          <span :class="['status', getClass(paymentDetails.status)]">
            {{ paymentDetails.status | enumValueByKey($const.EXAMINE_TYPE) }}
          </span>
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext992')">
          {{ paymentDetails.projectNo }}
        </a-descriptions-item>
        <a-descriptions-item
          :label="$t('all.autotext949')"
          :span="
            paymentDetails &&
            paymentDetails.type == this.$const.SUBJECTANDREESA.DAISHENGPI.value
              ? 2
              : 1
          "
        >
          {{ paymentDetails.researchCenterNo + ' - ' + paymentDetails.orgName }}
        </a-descriptions-item>
        <a-descriptions-item
          :label="$t('all.autotext1134')"
          v-if="
            paymentDetails &&
            paymentDetails.type != this.$const.SUBJECTANDREESA.DAISHENGPI.value
          "
        >
          {{ versionName || '' }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext229')">
          {{ paymentDetails.type | enumValueByKey($const.SUBJECTANDREESA) }}
        </a-descriptions-item>

        <a-descriptions-item :label="$t('all.autotext1157')" v-if="isShow">
          <!-- epv1.5 受试者取值字段后端确认变更 ptsName => bankAccount -->
          {{
            this.originDetail.unsubscribeStatus == 3
              ? '已注销'
              : paymentDetails.type ==
                this.$const.SUBJECTANDREESA.DAISHENGPI.value
              ? paymentDetails.researchDetailName
              : paymentDetails.ptsName
          }}
          <a
            @click="handleReceiveInfoVisible(true)"
            v-if="paymentDetails.type !== 2"
            >{{ $t('all.autotext896') }}</a
          >
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext1349')" v-else>
          {{
            this.originDetail.unsubscribeStatus == 3
              ? '已注销'
              : paymentDetails.type ==
                this.$const.SUBJECTANDREESA.DAISHENGPI.value
              ? paymentDetails.researchRoleName +
                ' - ' +
                paymentDetails.researchAccount
              : paymentDetails.ptsRoleName + ' - ' + paymentDetails.ptsNo
          }}
        </a-descriptions-item>
        <a-descriptions-item
          :label="$t('all.autotext473')"
          v-if="isShow && paymentDetails.offline === 1"
        >
          <span v-if="this.originDetail.unsubscribeStatus == 3">已注销</span>
          <span v-else>
            <span
              >{{ paymentDetails.bankType | enumValueByKey($const.BANK_TYPE) }}
              -
            </span>
            <span>{{ paymentDetails.bankName || '' }} </span>
            <!-- <span>{{ paymentDetails.bankNo | cardNoDeal }}</span> -->
            <span>{{ paymentDetails.bankNo }}</span>
          </span>
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext867')">
          ￥{{ paymentDetails.totalAmount }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext1537')">
          {{ paymentDetails.status | enumValueByKey($const.EXAMINE_TYPE) }}
        </a-descriptions-item>

        <a-descriptions-item :label="$t('all.autotext944')">
          {{ paymentDetails.payNo }}
        </a-descriptions-item>
        <a-descriptions-item v-if="isShowAdvancedPay" label="是否垫付">{{
          paymentDetails.advancedPay === null
            ? ''
            : paymentDetails.advancedPay === 0
            ? '否'
            : '是'
        }}</a-descriptions-item>
        <a-descriptions-item
          :label="$t('all.autotext1745')"
          :span="3"
          v-if="!originInfoIsNull && showHistoryApplyNo"
        >
          <a
            v-for="(item, index) in JSON.parse(paymentDetails.originInfo)"
            :key="index"
            v-show="item.applyNo !== paymentDetails.applyNo"
            style="margin-right: 10px"
            @click="handleOrigin(item)"
            >{{ item.applyNo }}</a
          >
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext550')" :span="3">
          {{ paymentDetails.applyReason }}
        </a-descriptions-item>
      </a-descriptions>
      <!-- 审批资料 -->

      <a-descriptions
        :title="$t('all.autotext1103')"
        style="margin-top: 20px"
      ></a-descriptions>
      <a-table
        ref="table"
        size="default"
        bordered
        :row-key="(record) => record.id"
        :pagination="false"
        :data-source="
          paymentDetails.fileArray ? JSON.parse(paymentDetails.fileArray) : []
        "
      >
        <a-table-column
          :title="$t('all.autotext334')"
          data-index="order"
          width="80px"
        >
          <template slot-scope="text, row, index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column
          :title="$t('all.autotext1706')"
          data-index="fileType"
          width="100px"
        >
          <template slot-scope="text, record">{{
            {
              1: $t('all.autotext1700'),
              2: $t('all.autotext1701'),
              3: $t('all.autotext1825'),
              4: $t('all.autotext1825')
            }[record.fileType]
          }}</template>
        </a-table-column>
        <!-- v-if="hasRole" -->
        <template>
          <a-table-column
            :title="$t('all.autotext215')"
            data-index="originalFile"
          >
            <!-- ( type && paymentDetails.status === -11 )  -->
            <template slot-scope="text, record">
              <a
                @click="lookPreview(record)"
                :class="{ disabledBtn: originDetail.unsubscribeStatus === 3 }"
              >
                {{ record.fileName }}
              </a>
            </template>
          </a-table-column>
          <a-table-column
            v-if="$options.filters.isPtsVisible()"
            :title="$t('all.autotext582')"
            data-index="afterFile"
          >
            <template slot-scope="text, record">
              <div class="afterfile">
                <template v-if="desensePassed(record)">
                  <a
                    class="filename"
                    @click="preview(record.afterFileUrl)"
                    :class="{
                      disabledBtn: originDetail.unsubscribeStatus === 3
                    }"
                    >{{ record.fileName }}</a
                  >
                  <!-- <a @click="editFile(record, index)">{{ $t('all.autotext1231') }}</a> -->
                </template>
                <template v-else>
                  <span class="grey">-</span>
                  <!-- <a @click="editFile(record, index, 2)">{{ $t('all.autotext236') }}</a> -->
                </template>
              </div>
            </template>
          </a-table-column>
        </template>
        <!-- <template v-else>
          <a-table-column
            :title="$t('all.autotext215')"
            data-index="originalFile"
          >
            <template slot-scope="text, record">
              <span v-if="type && paymentDetails.status === -11">{{
                record.fileName
              }}</span>
              <a v-else @click="preview(record.afterFileUrl || record.fileUrl)"
                >{{ record.fileName }}
              </a>
            </template>
          </a-table-column>
        </template> -->
      </a-table>
      <!-- 费用明细 -->
      <a-descriptions
        :title="$t('all.autotext12')"
        style="margin-top: 20px"
      ></a-descriptions>
      <a-table
        ref="table"
        size="default"
        bordered
        :row-key="(record) => record.id"
        :pagination="false"
        :data-source="originDetail.detailList"
      >
        <a-table-column :title="$t('all.autotext334')" key="id" data-index="id">
          <template slot-scope="text, row, index">{{ index + 1 }}</template>
        </a-table-column>
        <a-table-column
          :title="$t('all.autotext1278')"
          key="applyType"
          data-index="applyType"
        />
        <a-table-column
          :title="$t('all.autotext1049')"
          key="visitRecordInfo"
          data-index="visitRecordInfo"
          v-if="paymentDetails.type === 2"
        ></a-table-column>
        <a-table-column
          :title="$t('all.autotext850')"
          key="happenDate"
          data-index="happenDate"
          v-if="paymentDetails.type === 2"
        >
          <template slot-scope="text, record">
            {{
              record.happenDate
                ? $options.filters.moment(record.happenDate, 'YYYY-MM-DD')
                : '-'
            }}
          </template>
        </a-table-column>
        <a-table-column
          :title="$t('all.autotext674')"
          key="defaultBool"
          data-index="defaultBool"
        >
          <template slot-scope="text, row">
            {{
              row.defaultBool ? $t('all.autotext279') : $t('all.autotext957')
            }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1256')" key="amount">
          <template slot-scope="text, record">
            <span>{{ $t('money.unit') }}{{ record.amount }}</span>
            <span
              v-if="record.defaultAmt"
              style="margin-left: 40px; color: red"
              >{{ $t('all.autotext750') + '：￥' + record.defaultAmt }}</span
            >
            <span
              v-else-if="record.costMin && record.costMax"
              style="margin-left: 40px; color: red"
              >{{ $t('all.autotext1266') }}：￥{{ record.costMin }} - ￥{{
                record.costMax
              }}</span
            >
            <span
              v-else-if="record.costMin"
              style="margin-left: 40px; color: red"
              >{{ $t('all.autotext1266') }}：{{ $t('all.autotext495') }}￥{{
                record.costMin
              }}</span
            >
            <span
              v-else-if="record.costMax"
              style="margin-left: 40px; color: red"
              >{{ $t('all.autotext1266') }}：0 - ￥{{ record.costMax }}</span
            >
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1258')" key="fileList">
          <template slot-scope="text, record">
            <!-- 费用文件预览 -->
            <!-- <ViewFile v-if="getFileList(record).length" :data="getFileList(record)">
              <a>{{ $t('all.autotext568') }}</a>
            </ViewFile> -->
            <div v-if="getFileList(record).length">
              {{ getFileListName(record) }}
            </div>
            <span v-else>{{ $t('all.autotext263') }}</span>
          </template>
        </a-table-column>
        <!-- <a-table-column :title="$t('all.autotext1709')" key="comment" data-index="comment" /> -->
        <!-- <a-table-column title="操作" v-if="canAudit">
          <template slot-scope="record">
            <a @click="specialCheck(record)" v-if="isSiteCrc && showSpecialCheck(record)">审批</a>
          </template>
        </a-table-column> -->
      </a-table>
      <!-- 审批流 -->
      <!-- <a-descriptions title="审批流" style="margin-top: 24px;"></a-descriptions> -->
      <!-- <approveSteps :data="originDetail.flowNodeList"></approveSteps> -->
      <ApprovePreview
        :nodes="originDetail.flowNodeList"
        type="view"
        :offline="offline"
        :title="$t('all.autotext761')"
        :currentNodeCode="currentNodeCode"
      />
      <!-- 个税情况 -->
      <a-descriptions
        :title="$t('all.autotext222')"
        style="margin-top: 20px"
        v-if="isShowTax"
      >
        <a-descriptions-item :label="$t('all.autotext867')">
          {{ $t('money.unit') }}{{ paymentDetails.totalAmount }}
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext806')">
          <span style="margin-right: 10px; width: 5rem">{{
            paymentDetails.personalTax != null
              ? $t('money.unit') + paymentDetails.personalTax
              : $t('all.autotext609')
          }}</span>
        </a-descriptions-item>
        <a-descriptions-item :label="$t('all.autotext1173')">
          {{ $t('money.unit')
          }}{{
            (
              paymentDetails.totalAmount -
              (paymentDetails.personalTax != null
                ? paymentDetails.personalTax
                : 0)
            ).toFixed(2)
          }}
        </a-descriptions-item>
      </a-descriptions>
      <p v-if="paymentDetails.taxRemark">
        {{ $t('all.autotext983') }}：{{ paymentDetails.taxRemark }}
      </p>
      <!-- 申请记录 -->

      <a-descriptions
        :title="$t('all.autotext1282')"
        style="margin-top: 24px"
      ></a-descriptions>
      <a-steps
        direction="vertical"
        :current="costRecords.length - 1"
        size="small"
      >
        <a-step
          v-for="item in costRecords"
          :status="
            item.status == $const.FEE_CHECK_STATUS.FAIL.value ||
            item.status == $const.FEE_CHECK_STATUS.REJECT.value ||
            item.status == $const.FEE_CHECK_STATUS.CLOSE.value
              ? 'error'
              : ''
          "
          :key="item.id"
        >
          <template slot="title">
            {{
              item.processTitle === $t('all.autotext699')
                ? $t('all.autotext369')
                : item.processTitle
            }}
            <div class="red" v-if="!item.children && item.refuseReason">
              {{ $t('all.autotext1568') }}{{ item.refuseReason }}
            </div>
            <div
              v-if="
                item.status == $const.FEE_CHECK_STATUS.CLOSE.value &&
                item.processTitle === $t('费用申请关闭')
              "
            >
              <div>{{ $t('关闭原因：') }}{{ item.closeReason }}</div>
              <div v-if="item.closeReason">
                <a @click="preview(item.closeFile)" class="red">{{
                  item.closeFileName
                }}</a>
              </div>
            </div>
          </template>
          <template slot="description">
            <div v-if="!item.children">
              <div class="step-mark" v-if="item.comment">
                {{ item.comment }}
              </div>
              <span>{{ item.desc }} </span>
              <a
                v-if="
                  item.processTitle === $t('all.autotext699') &&
                  item.proofUrl &&
                  $options.filters.isPtsVisible()
                "
                style="margin-left: 10px"
                target="_blank"
                :href="item.proofUrl | dealImageUrl"
                >{{ $t('all.autotext512') }}</a
              >
              <a
                v-if="
                  (item.processTitle === $t('all.autotext1453') ||
                    item.processTitle === $t('all.autotext563')) &&
                  item.proofUrl &&
                  $store.getters.roles[0]?.ptsVisible === 1
                "
                style="margin-left: 10px"
                target="_blank"
                :href="item.proofUrl | dealImageUrl"
                :class="{ disabledBtn: originDetail.unsubscribeStatus === 3 }"
                >{{ $t('all.autotext349') }}</a
              >

              <a-button
                v-if="
                  isShowUrgeBtn(item) &&
                  paymentDetails.status !== -11 &&
                  paymentDetails.status !== -12
                "
                type="primary"
                style="margin-left: 10px"
                @click="clickQuickStart(item)"
              >
                {{ $t('all.autotext1129') }}
              </a-button>
            </div>
            <template v-else>
              <div v-for="(k, i) in item.children" :key="i">
                {{ k.desc }}
                <span class="red" v-if="k.refuseReason"
                  >【{{ k.refuseReason }}】</span
                >
                <a-button
                  v-if="
                    isShowUrgeBtn(item) &&
                    paymentDetails.status !== -11 &&
                    paymentDetails.status !== -12
                  "
                  type="primary"
                  style="margin-left: 10px"
                  @click="clickQuickStart(item)"
                >
                  {{ $t('all.autotext1129') }}
                </a-button>
              </div>
            </template>
            <div
              v-if="item.auditArray && !item.auditArray?.includes('undefined')"
            >
              <div v-for="(v, i) in JSON.parse(item.auditArray)" :key="i">
                <a
                  @click="preview(v.url)"
                  :class="{ disabledBtn: originDetail.unsubscribeStatus === 3 }"
                  >{{ v.fileName }}</a
                >
              </div>
            </div>
          </template>
        </a-step>
      </a-steps>
      <!-- 重新提交按钮   -->
      <div style="padding-top: 20px; display: flex">
        <div
          v-if="
            (paymentDetails.type === 2
              ? $auth('PROJCET.PROJECT_FEE_PATIENT_RESUBMIT')
              : $auth('PROJCET.PROJECT_FEE_RESEARCHER_RESUBMIT')) &&
            ($store.getters.userInfo.id === paymentDetails.createrId ||
              $store.getters.userInfo.id === paymentDetails.receiveCreaterId) &&
            (paymentDetails.status === -1 || paymentDetails.status === -11) &&
            paymentDetails.valid === 1 &&
            this.showUrge
          "
        >
          <a-button style="margin-left: 10px" @click="$router.go(-1)">
            {{ $t('all.autotext76') }}
          </a-button>
          <!-- 已注销受试者不展示重新提交按钮 -->
          <a-button
            v-if="originDetail.unsubscribeStatus < 2"
            type="primary"
            style="margin-left: 10px"
            @click="reSubmit"
          >
            {{ $t('all.autotext1456') }}
          </a-button>
        </div>
        <a-button
          type="danger"
          style="margin-left: 10px"
          @click="handleCloseApply(true)"
          v-if="
            ($store.getters.userInfo.id === paymentDetails.createrId ||
              $store.getters.userInfo.id === paymentDetails.receiveCreaterId) &&
            paymentDetails.status != 60 &&
            paymentDetails.status != -12 &&
            paymentDetails.status != 51 &&
            paymentDetails.status != 70 &&
            this.showUrge
          "
        >
          {{ $t('all.closeApply') }}
        </a-button>
      </div>

      <!-- 费用科目快照 -->
      <!-- <a-descriptions :title="$t('all.autotext887')" style="margin-top: 24px;"></a-descriptions>
      <a-table
        :data-source="originDetail.flowFeeCategoryList"
        :rowKey="record => record.id"
        :pagination="false"
        bordered
      >
        <a-table-column :title="$t('all.autotext1278')" key="applyType" data-index="applyType"></a-table-column>
        <a-table-column :title="$t('all.autotext674')" key="defaulted" data-index="defaulted">
          <template slot-scope="text, row">
            {{ row.defaulted ? $t('all.autotext279') : $t('all.autotext957') }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext750')" key="amt" data-index="amt">
          <template slot-scope="text">
            ￥{{ text }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('all.autotext1103')" key="apv" data-index="apv">
          <template slot-scope="text, row">
            {{ row.apv ? $t('all.autotext279') : $t('all.autotext263') }}
          </template>
        </a-table-column>
      </a-table> -->
      <a-modal
        :visible="receiveInfoVisible"
        :title="$t('all.autotext922')"
        width="500px"
        :footer="null"
        @cancel="handleReceiveInfoVisible(false)"
      >
        <div class="info">
          <span class="info-item">{{ $t('all.autotext977') }}:</span
          >{{ userDetail.name }}
        </div>
        <div class="info">
          <span class="info-item">{{ $t('all.autotext1104') }}:</span
          >{{ userDetail.gender }}
        </div>
        <div class="info">
          <span class="info-item">{{ $t('all.autotext936') }}:</span
          >{{ userDetail.idCardNO }}
        </div>
      </a-modal>
      <specialCheckModel
        v-model="specialCheckVisible"
        :req="specialCheckReq"
        @success="specialCheckSuccess"
      />
    </div>
    <!-- 图片预览 -->
    <a-modal
      width="50%"
      :visible="imgVisible"
      :footer="null"
      @cancel=";(imgVisible = false), (itemFileUrl = '')"
    >
      <div class="image">
        <viewer>
          <img :src="itemFileUrl | dealImageUrl" />
        </viewer>
      </div>
    </a-modal>
    <DetailView ref="detailView" :type="1" />
    <!-- 关闭理由 -->
    <AuditFailure
      :visible="closeApplyVisible"
      @handleCloseApply="closeApplyVisible = false"
      @uploadClickConfirm="uploadClickConfirm"
      ref="AuditFailure"
    />
  </div>
</template>

<script>
import specialCheckModel from './components/specialCheckModel'
import AuditFailure from './components/auditFailure'
import store from '@/store'
import {
  getApplyDetail,
  requestCostUrge,
  getVersionList,
  closeApply
} from '@/api/cost/cost'
import moment from 'moment'
// import approveSteps from '../overview/detail/responsible/components/approveSteps'
// import ViewFile from './researcher/ViewFile'
import { getSiteCrcByPtsId, getUrgeStatus } from '@/api/cost/audit'
import { getUserNoByIds } from '@/api/account/user'
import { getInfo, getFeeUserInfo } from '@/api/login'
import ApprovePreview from './components/approvePreview'
import html2canvas from 'html2canvas'
import { jsPDF as JsPDF } from 'jspdf'

export default {
  name: 'fee-detail',
  props: {
    // 是否在弹框内，是的话getInfo在外面操作
    isModal: {
      type: Boolean,
      default: false
    },
    canAudit: {
      type: Boolean,
      default: false
    },
    showUrge: {
      type: Boolean,
      default: false
    },
    costId: [Number, String],
    type: {
      type: Number,
      default: 0
    }
  },
  components: {
    specialCheckModel,
    ApprovePreview,
    AuditFailure,
    DetailView: () => import('@/views/cost-auditing/detail.vue')
  },
  data() {
    return {
      receiveInfoVisible: false,
      specialCheckVisible: false,
      specialCheckReq: {},
      userDetail: {},
      urgeMap: null,
      originDetail: {},
      paymentDetails: {},
      costRecords: [],
      chekList: [],
      versionName: '',
      isSiteCrc: true, // 是否当前site的CRC，不是CRC的时候不需要这个判段，所以默认是true好一点
      isShow: false, // crc、pi和财务可以看到收款人员和账号，其他角色只能看到收款人员id且看不到账号
      currentNodeCode: '', // 当前审批节点code
      offline: 1,
      imgVisible: false,
      itemFileUrl: '',
      closeApplyVisible: false
    }
  },
  computed: {
    originInfoIsNull() {
      const v = this.paymentDetails?.originInfo
        ? JSON.parse(this.paymentDetails.originInfo)
        : []
      return !v || v.length === 0
    },
    showHistoryApplyNo() {
      // 遍历历史申请单，有1个不同即显示
      const v = this.paymentDetails?.originInfo
        ? JSON.parse(this.paymentDetails.originInfo)
        : []
      return v.some((item) => item.applyNo !== this.paymentDetails.applyNo)
    },
    isShowAdvancedPay() {
      return (
        this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.YW_ADMIN.value) ||
        this.$options.filters.isHasAuth(
          this.$const.ROLE_TYPE.PROJECT_ADMIN.value
        ) ||
        this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value)
      )
    },
    isShowTax() {
      // 审核通过后，个税没有办理的情况下，其他非财务角色查看审核记录，不能查看个税情况
      if (
        this.$store.getters.role.code !== 'SYS_FINANCE' &&
        this.paymentDetails.personalTax == null
      ) {
        return false
      }
      if (this.paymentDetails.type === 2) {
        return false
      }
      return (
        this.paymentDetails.personalTax != null
      )
    },
    hasRole() {
      if (this.paymentDetails.type === 2) {
        return ['SYS_FINANCE', 'CRC', 'Investigator'].includes(
          this.$store.getters.roles[0].code
        )
      } else {
        return ['SYS_FINANCE', 'CRA', 'PM', 'Investigator'].includes(
          this.$store.getters.roles[0].code
        )
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      window.scroll({ top: 0, left: 0 })
    })
    this.checkRole()
    !this.isModal && this.getInfo()
  },
  methods: {
    // 打开关闭申请弹框
    handleCloseApply(flag = false) {
      this.closeApplyVisible = flag
    },

    // 关闭弹窗确认回调
    uploadClickConfirm(value) {
      // console.log('============', value)
      // const status = value.status === true ? 1 : -1
      this.$refs.AuditFailure.confirmLoading = true
      let data = {
        id: this.costId,
        closeReason: value.closeReason,
        closeFile: value.closeFile,
        closeFileName: value.closeFileName
      }
      closeApply(data)
        .then((res) => {
          // console.log(res, '1213')
          this.$refs.AuditFailure.confirmLoading = false
          this.$refs.AuditFailure.form = {}
          this.$message.success(this.$t('all.autotext470'))
          this.handleCloseApply()
          this.getInfo()
        })
        .catch(() => {
          this.$refs.AuditFailure.confirmLoading = false
        })
    },

    // 脱敏通过
    desensePassed({ fileUrl, afterFileUrl }) {
      return afterFileUrl && afterFileUrl !== fileUrl
    },
    // 单文件预览
    preview(fileUrl) {
      const formatImg = /(\.(gif|png|jpg|jpeg|webp|svg|psd|bmp|tif))$/i
      if (formatImg.test(fileUrl)) {
        this.itemFileUrl = fileUrl
        this.imgVisible = true
      } else {
        // 打开空白页 展示文件
        const fullFileUrl = this.$options.filters.dealImageUrl(fileUrl)
        window.open(fullFileUrl, '_blank')
      }
    },
    // 受试者可见不可见预览
    lookPreview(record) {
      const fileUrl =
        !this.$options.filters.isPtsVisible() && record.afterFileUrl
          ? record.afterFileUrl
          : record.fileUrl
      this.preview(fileUrl)
    },
    getClass(status) {
      switch (status) {
        case -11:
          return 'back'
        default:
          return ''
      }
    },
    getFileList(record) {
      const { fileList, fileArr } = record
      if (!fileArr) {
        return fileList
      }
      const fileArrList = JSON.parse(fileArr)
      return fileArrList.map((item) => {
        return {
          fileName: item.fileName,
          fileUrl: item.afterUrl || item.originalUrl
        }
      })
    },
    getFileListName(record) {
      const { fileList, fileArr } = record
      if (!fileArr) {
        return fileList
          .map((item) => item.fileName.replace(/\.[^/.]+$/, ''))
          .join(',')
      }
      const fileArrList = JSON.parse(fileArr)
      return fileArrList
        .map((item) => item.fileName.replace(/\.[^/.]+$/, ''))
        .join(',')
    },
    /*
     * 重新提交费用申请
     * */
    reSubmit() {
      if (this.paymentDetails.type === 1) {
        this.$router.push({
          name: 'AddResearcher',
          query: {
            pname: this.$store.state.user.project.name,
            id: this.paymentDetails.proId,
            costId: this.costId
          }
        })
      } else if (this.paymentDetails.type === 2) {
        this.$router.push({
          name: 'AddSubject',
          query: {
            pname: this.$store.state.user.project.name,
            id: this.paymentDetails.proId,
            costId: this.costId
          }
        })
      } else {
        return null
      }
    },
    handleReceiveInfoVisible(flag = false) {
      this.receiveInfoVisible = flag
    },
    async getFeeUserInfo(data) {
      const params = {}
      if (data.type === this.$const.SUBJECTANDREESA.DAISHENGPI.value) {
        params.researchDetailId = data.researchDetailId
      } else {
        params.ptsId = data.ptsId
      }
      this.userDetail = await getFeeUserInfo(params)
    },
    async getUserRole(proId) {
      const res = await getInfo({ proId })
      this.$store.commit('SET_ROLES', res.roles)
      this.$store.commit('SET_INFO', res.user)
      this.$store.commit('SET_PMS', res.pms)
    },
    showSpecialCheck(row) {
      return this.chekList.some(
        (v) => v.proFeeApplyDetailId === row.id && v.needCheck
      )
    },
    async specialCheck(row) {
      this.specialCheckReq = {
        id: this.paymentDetails.id,
        detailId: row.id,
        applyType: row.applyType,
        status: '',
        refuseReason: ''
      }
      this.specialCheckVisible = true
    },
    async specialCheckSuccess() {
      await this.getInfo()
      this.$emit('refresh')
    },
    getCheckList() {
      const needCheckNodeList = this.originDetail.processList.filter(
        (v) => v.resultOrAction === 2 && v.proFlowNodeCode.slice(3) !== '0000'
      )
      this.chekList = needCheckNodeList.map((v) => {
        let needCheck
        const isRole = this.$store.getters.role.code === v.roleCode
        // 到人
        if (v.processType === 1) {
          needCheck = v.processorId
            ? v.processorId
                .split(',')
                .includes(String(this.$store.state.user.info.id))
            : false
        } else {
          needCheck = isRole
        }
        return {
          ...v,
          needCheck
        }
      })
    },
    checkUrge(item) {
      if (!this.showUrge) {
        return false
      }
      // 待处理
      return (
        item.resultOrAction === 2 &&
        this.paymentDetails.createrId === store.getters.userInfo.id
      )
    },
    // 催办
    clickQuickStart(row) {
      if (!this.urgeMap[row.id])
        return this.$message.warning(this.$t('all.autotext772'))
      requestCostUrge({
        id: this.costId,
        processId: row.id
      }).then((res) => {
        this.urgeMap[row.id] = false
        this.$message.success(this.$t('all.autotext774'))
      })
    },
    // 判断角色
    checkRole() {
      this.isShow =
        this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.CRC.value) ||
        this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.PI.value) ||
        this.$options.filters.isHasAuth(this.$const.ROLE_TYPE.FINANCE.value)
          ? 1
          : 0
    },
    getUserCode(ids, list) {
      const res = ids
        .split(',')
        .map((v) => {
          const user = list.find((item) => item.id === +v)
          return user ? user.userNo : ''
        })
        .filter(Boolean)
        .toString()
      return res ? '-' + res : ''
    },
    getCurrentNode(nodeList, processList) {
      let current = null
      for (let i = nodeList.length - 1; i >= 0; i--) {
        const item = nodeList[i]
        const targetProcess = processList.find(
          (v) => v.proFlowNodeCode === item.code
        )
        if (
          targetProcess &&
          targetProcess.status !== 0 &&
          targetProcess.status !== 6
        ) {
          current = item.code
          break
        }
      }
      return current
    },
    async getInfo() {
      // 获取详情
      const res = await getApplyDetail({ id: this.costId })
      const that = this
      this.costRecords = []
      this.originDetail = res
      const { processList, flowNodeList } = res
      this.offline = res.feeApplyDto.offline
      this.paymentDetails = res.feeApplyDto
      this.getFeeUserInfo(this.paymentDetails)
      await this.getUserRole(res.feeApplyDto.proId)
      await this.getIsSiteCrc()

      const needUrgeData = []
      if (processList && processList.length) {
        if (this.paymentDetails.status !== 60) {
          const currentNode = this.getCurrentNode(
            res.flowNodeList,
            res.processList
          )
          this.currentNodeCode = currentNode || 'start'
        } else {
          this.currentNodeCode = 'end'
        }
        const processors = processList.flatMap((process) => {
          if (!process.processorId) return []
          return process.processorId ? process.processorId.split(',') : ''
        })

        const userCodeList = await getUserNoByIds({
          ids: processors.toString(),
          proId: res.feeApplyDto.proId
        })
        // 处理主节点
        // eslint-disable-next-line
        function dealItem(item) {
          let desc = item.processTime
            ? `${moment(item.processTime).format('YYYY-MM-DD HH:mm:ss')} `
            : item.content
          if (item.processTitle === that.$t('all.autotext1453')) {
            // 银行付款
            if (item.status === 7) {
              desc += `${that.$t('all.autotext1032')}${
                res.feeApplyDto.payNo
              } 【${that.$t('all.autotext1152')}】`
            } else if (item.status === -2) {
              desc += `${that.$t('all.autotext127')}${item.refuseReason}`
            }
          } else if (item.processTitle === that.$t('all.autotext563')) {
            // 财务手动打款
            desc = item.content
          } else if (item.processorId) {
            // const userCode = item.roleCode === 'Investigator' ? `-${item.processorAccount}` : that.getUserCode(item.processorId, userCodeList)
            //  PRIME 审批 不显示项目管理员和账号
            const userCode =
              item.processTitle.includes('PRIME') &&
              item.processorRoleName === '项目管理员'
                ? `${
                    item.processorAccount
                      ? item.processorAccount
                      : item.processorName
                  }`
                : `${item.processorRoleName ? item.processorRoleName : ''}${
                    item.processorRoleName ? ' - ' : ''
                  }${
                    item.processorAccount
                      ? item.processorAccount
                      : item.processorName
                  }`
            if (item.processTitle === that.$t('all.autotext699')) {
              // 申报个税
              if (
                res.feeApplyDto.personalTax === 0 ||
                res.feeApplyDto.personalTax == null
              ) {
                desc += `${userCode} ${that.$t('all.autotext1347')}`
              } else {
                desc += `${userCode} ${that.$t('all.autotext18')} ${that.$t(
                  'money.unit'
                )}${
                  res.feeApplyDto.personalTax
                } 【${that.$options.filters.enumValueByKey(
                  item.status,
                  that.$const.FEE_CHECK_STATUS
                )}】`
              }
            } else if (
              item.processTitle === that.$t('all.autotext1375') &&
              item.content
            ) {
              desc = item.content
            } else {
              if (item.status === 5) {
                desc += `${userCode} 【${
                  // 之前有区分 财务提交 还是项目管理员提交
                  item.roleCode === 'SYS_FINANCE'
                    ? '提交重新打款申请'
                    : '提交重新打款申请'
                }】`
              } else {
                desc += `${userCode} 【${that.$options.filters.enumValueByKey(
                  item.intermediate === 1 && [1, -1].includes(item.status)
                    ? item.status * 100
                    : item.status,
                  that.$const.FEE_CHECK_STATUS
                )}】`
              }
            }
          }
          return {
            ...item,
            desc: item.resultOrAction === 2 ? item.content : desc
          }
        }
        // 处理特批节点
        // eslint-disable-next-line
        function dealNodeItem(item) {
          const userCode =
            item.roleCode === 'Investigator'
              ? item.processorNo
              : that.getUserCode(item.processorId, userCodeList)
          const processor = userCode || ''
          const processTime = item.processTime
            ? moment(item.processTime).format('YYYY-MM-DD HH:mm:ss')
            : ''
          return {
            ...item,
            desc: `${processTime} ${item.applyType} ${this.$t(
              'all.autotext1006'
            )} ${
              item.roleName
            }${processor} 【${that.$options.filters.enumValueByKey(
              item.status,
              that.$const.FEE_CHECK_STATUS
            )}】`
          }
        }

        let condition = null
        processList.forEach((item, i) => {
          if (!item.showInFront) return
          if (this.checkUrge(item)) {
            needUrgeData.push({
              id: item.proFeeApplyId,
              processId: item.id
            })
          }
          // 找到条件节点
          const isCNode = res.flowNodeList.some(
            (v) => v.code === item.proFlowNodeCode && v.nodeType === 2
          )
          if (isCNode) {
            condition = item
          } else {
            if (condition && item.proFlowNodeCode.slice(3) !== '0000') {
              // 将子节点数据结构改为树形
              if (!condition.children) condition.children = []
              condition.children.push(dealNodeItem(item))
              if (condition && i === processList.length - 1) {
                this.costRecords.push(condition)
              }
            } else {
              condition && this.costRecords.push(condition)
              condition = null
              this.costRecords.push(dealItem(item))
            }
          }
        })
        if (this.offline === 2) {
          this.costRecords = this.costRecords.filter((item) => {
            return (
              item.processTitle !== this.$t('all.autotext826') &&
              item.processTitle !== this.$t('all.autotext854')
            )
          })
        }

        this.costRecords.forEach((item) => {
          if (item.status === 7) {
            item.desc = item.desc + `【${this.$t('all.autotext1534')}】`
          }
        })
      }
      this.$emit(
        'init',
        res.feeApplyDto,
        processList,
        this.isSiteCrc,
        flowNodeList,
        this.currentNodeCode
      )

      this.paymentDetails.type === 2 && this.getVersionList(this.paymentDetails)
      this.getCheckList()
      this.getNeedUrgeData(needUrgeData)
    },
    async getIsSiteCrc() {
      if (this.paymentDetails.type !== 2) return
      if (this.$store.getters.role.code !== 'CRC') return
      const crcId = await getSiteCrcByPtsId({
        proId: this.paymentDetails.proId,
        ptsId: this.paymentDetails.ptsId
      })
      this.isSiteCrc = crcId === this.$store.state.user.info.id
    },
    getVersionList({ proId, visitId }) {
      getVersionList({ proId }).then((res) => {
        res.forEach((item) => {
          if (item.id === visitId) {
            this.versionName = item.name
          }
        })
      })
    },
    // 获取列表所有的id，一次性去请求是否需要催办
    async getNeedUrgeData(needUrgeData) {
      const map = {}
      for (const val of needUrgeData) {
        map[val.processId] = await getUrgeStatus(val)
      }
      this.urgeMap = map
    },
    isShowUrgeBtn(row) {
      if (row.phaseType !== 1) return false
      if (row.processTitle === this.$t('all.autotext1027')) return false
      return this.urgeMap && this.urgeMap[row.id] !== undefined
    },
    // 导出页面为pdf
    exportToPDF() {
      // 获取包含页面内容的div元素
      const content = this.$refs.pdfContent
      // 使用html2canvas将div转为canvas
      html2canvas(content, {
        dpi: window.devicePixelRatio * 4, // 将分辨率提高到特定的DPI 提高四倍
        scale: 2
      }).then((canvas) => {
        const imgData = canvas.toDataURL('image/png')
        const pdf = new JsPDF('l', 'mm', 'a3')
        // 计算页面宽高
        const pdfWidth = pdf.internal.pageSize.getWidth()
        const pdfHeight = pdf.internal.pageSize.getHeight()

        // 设置页面边距
        const marginTop = 10 // 顶部边距，单位为mm
        const marginBottom = 10 // 底部边距，单位为mm
        const marginLeft = 10 // 左侧边距，单位为mm
        const marginRight = 10 // 右侧边距，单位为mm
        // 将canvas内容添加到PDF中
        pdf.addImage(
          imgData,
          'PNG',
          marginLeft,
          marginTop,
          pdfWidth - marginLeft - marginRight,
          pdfHeight - marginTop - marginBottom
        )

        // 保存或下载PDF
        pdf.save('page.pdf')
      })
    },
    handleOrigin(item) {
      this.$refs.detailView.open(item.costId)
    }
  },
  beforeDestroy() {
    // if (this.$route.path === '/message') {
    //   this.$store.dispatch('ClearProject')
    // }
  }
}
</script>
<style scoped lang="less">
.status {
  margin: 0 20px;
  padding: 3px 10px;
  border: 1px solid #70b603;
  border-radius: 40px;
  color: #70b603;

  &.back {
    color: red;
    border: 1px solid red;
  }
}

.red {
  color: #e04b28;
  white-space: pre-line;
  word-wrap: break-word;
}

.step-mark {
  color: #333;
  white-space: pre-line;
  word-wrap: break-word;
}

.info {
  display: flex;
  margin-bottom: 15px;

  &-item {
    width: 100px;
    text-align: right;
    margin-right: 10px;
  }
}

.exportPdf-wrap {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.image {
  img {
    display: block;
    width: 80%;
    margin: 10px auto;
  }
}

/deep/.ant-descriptions-item-label {
  white-space: nowrap !important;
}

/deep/.ant-descriptions-item-content {
  word-break: break-all;
}

.disabledBtn {
  cursor: not-allowed;
  color: rgba(0, 0, 0, 0.25);
  pointer-events: none;
}
</style>
